<template>
  <div class="app-container">
    <el-card>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="关键字:">
          <el-input v-model="queryForm.keyword" placeholder="请输入关键字" style="width: 128px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
          />
        </el-form-item>
        <el-form-item label="日期范围:">
          <el-date-picker
            v-model="queryForm.dateRange"
            :editable="false"
            style="width: 256px;"
            size="small"
            type="daterange"
            align="right"
            unlink-panels
            value-format="yyyy/MM/dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="fetchData(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        stripe
      >
        <el-table-column align="center" label="编号" width="84">
          <template v-slot="scope">
            {{ scope.row.tid }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="工单名称">
          <template v-slot="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="创建时间" min-width="65">
          <template v-slot="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.created_at.slice(0,10) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="status-col" label="操作">
          <template v-slot="scope">
            <el-button size="mini" icon="el-icon-edit" type="primary" @click="$router.push({name:'editDraft',params:{draft:scope.row}})">编辑</el-button>
            <el-button size="mini" icon="el-icon-edit" type="primary" @click="openPublish(scope.row.tid,scope.row.header_value)">提交</el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="confirmDelete(scope.row.tid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-dialog title="提交新工单" :visible.sync="submitDialogFormVisible">
          <el-tabs v-model="activeTabName" :stretch="true">
            <el-tab-pane label="作为主工单" name="first">
              <el-form ref="ruleForm" :model="queryUser" status-icon class="demo-ruleForm" style="margin-left: 12px">
                <el-form-item>
                  <span>该操作将直接提交工单并进入流转状态，请确认工单是否正确填写。</span>
                </el-form-item>
                <el-form-item label="工单流转至:">
                  <el-input v-model="queryUser.keyword" placeholder="请输入姓名或工号" style="width: 200px;"
                            prefix-icon="el-icon-search"
                            size="small"
                            @keyup.enter.native="searchUser(1)"
                  />
                  <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px"
                             @click="searchUser(1)">搜索
                  </el-button>
                </el-form-item>
              </el-form>
              <el-table
                v-loading="listLoading"
                :data="searchList"
                style="width: 100%"
              >
                <el-table-column
                  label="工号"
                  prop="uid"
                />
                <el-table-column
                  label="姓名"
                  prop="username"
                />
                <el-table-column
                  align="right"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="handleTo(scope.row.uid)"
                    >流转给TA
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
                <el-pagination
                  :page-size="5"
                  background
                  layout="prev, pager, next"
                  :current-page.sync="currentPage"
                  :total="total"
                  @current-change="searchUser(currentPage)"
                />
              </div>
              <div style="width: 100%;display: flex;margin-top: 24px;">
                <el-button @click="submitDialogFormVisible = false">取消</el-button>
                <div style="flex-grow: 1"></div>
                <el-button type="primary" @click="handleTo($store.getters.userInfo.uid)">流转给自己</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane active-name="second" label="作为子工单">
              <el-form ref="childForm" :model="queryChildOrder" status-icon class="demo-ruleForm" style="margin-left: 12px">
                <el-form-item>
                  <span>该操作将直接提交工单并进入流转状态，请确认工单是否正确填写。</span>
                </el-form-item>
                <el-form-item label="加入主工单:">
                  <el-input v-model="queryChildOrder.keyword" placeholder="请输入主工单关键字" style="width: 200px;"
                            prefix-icon="el-icon-search"
                            size="small"
                            @keyup.enter.native="searchMainOrder(childOrderCurrentPage)"
                  />
                  <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px"
                             @click="searchMainOrder(childOrderCurrentPage)">搜索
                  </el-button>
                </el-form-item>
              </el-form>
              <el-table
                v-loading="childOrderListLoading"
                :data="childOrderList"
                style="width: 100%"
              >
                <el-table-column
                  label="工单编号"
                  prop="tid"
                />
                <el-table-column
                  label="工单名称"
                  prop="name"
                />
                <el-table-column
                  align="right"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="submitToMainOrder(scope.row.tid)"
                    >作为子工单
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
                <el-pagination
                  :page-size="5"
                  background
                  layout="prev, pager, next"
                  :current-page.sync="childOrderCurrentPage"
                  :total="childOrderTotal"
                  @current-change="searchMainOrder(childOrderCurrentPage)"
                />
              </div>
              <div style="width: 100%;display: flex;margin-top: 24px;">
                <el-button @click="submitDialogFormVisible = false">取消</el-button>
                <div style="flex-grow: 1"></div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-dialog>
        <el-pagination
          :page-size="pageSize"
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :total="total"
          @current-change="fetchData(currentPage)"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { DATE_RANGE_OPTIONS, PAGE_SIZES } from '@/utils/common'
import { deleteDraft, draftToFreeStore, getDraftList, moveOrder, publishDraft, toFreeStore } from '@/api/table'
import { findUser } from '@/api/user'
import {getMyCreatedOrderList, setMainOrder} from "@/api/order";

export default {
  name: 'MyDraft',
  data() {
    return {
      queryChildOrder: {
        keyword: '',
      },
      childOrderListLoading: false,
      childOrderList: [],
      childOrderTotal: 0,
      childOrderCurrentPage: 1,
      childOrderPageSize: PAGE_SIZES,
      pickerOptions: DATE_RANGE_OPTIONS,
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      submitDialogFormVisible: false,
      activeTabName: 'first',
      deliverDialogFormVisible: false,
      queryForm: {
        keyword: '',
        dateRange: null
      },
      queryUser: {
        keyword: ''
      },
      list: [],
      listLoading: true,
      toPublish: null,
      dialogCurrentPage: 1,
      dialogTotal: 0,
      searchList: []

    }
  },
  created() {
    this.fetchData(1)
  },
  methods: {
    searchMainOrder(page) {
      this.childOrderListLoading = true
      let param = {
        name: this.queryChildOrder.keyword,
        filter: -1,

      }
      getMyCreatedOrderList(PAGE_SIZES, page, param).then(response => {
        this.childOrderList = response.data.data.filter(item => item.type === 1)
        this.childOrderTotal = response.data.total
        this.childOrderListLoading = false
      })
    },
    submitToMainOrder(ftid) {
      publishDraft(this.toPublish).then(res => {
        console.log(res)
        setMainOrder(this.toPublish, ftid).then(res => {
          this.$message.success('发布表单成功')
          setTimeout(() => {
            this.$router.push('/workOrderSys/myCreation')
          }, 500)
        })
      }).catch(() => {
        window.location.reload()
      })
    },
    handleTo(uid) {
      publishDraft(this.toPublish).then(res => {
        moveOrder(res.data.tid, uid).then(res => {
          this.$message({
            type: 'success',
            message: '流转成功!'
          })
          this.submitDialogFormVisible = false
          this.queryUser.keyword = ''
          this.searchUser(1)
          this.fetchData(1)
        }).catch(() => {
          window.location.reload()
        })
      }).catch(() => {
        window.location.reload()
      })
    },
    searchUser(page) {
      this.listLoading = true
      findUser(5, page, { name: this.queryUser.keyword }).then(response => {
        this.searchList = response.data.data
        this.dialogTotal = response.data.total
        this.listLoading = false
      })
    },
    subToFreeStore() {
      draftToFreeStore(this.toPublish).then(res => {
        this.$message.success('提交成功')
        this.submitDialogFormVisible = false
        this.fetchData(1)
      })
    },
    getNewDay(dateTemp, days) {
      dateTemp = dateTemp.split('-')
      const nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]) // 转换为MM-DD-YYYY格式
      const millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000)
      const rDate = new Date(millSeconds)
      const year = rDate.getFullYear()
      let month = rDate.getMonth() + 1
      if (month < 10) month = '0' + month
      let date = rDate.getDate()
      if (date < 10) date = '0' + date
      return (year + '-' + month + '-' + date)
    },
    openPublish(tid, header_value) {
      const data = JSON.parse(header_value)
      this.toPublish = tid
      this.submitDialogFormVisible = true
    },
    publish(tid) {
      publishDraft(tid).then(res => {
        this.$message.success('发布表单成功')
        if (this.list.length === 1) {
          this.currentPage--
        }
        this.fetchData(this.currentPage)
      })
    },
    fetchData(page) {
      this.listLoading = true
      const params = {
        name: this.queryForm.keyword
      }
      if (this.queryForm.dateRange) {
        console.log(this.queryForm.dateRange)
        params['begin'] = this.queryForm.dateRange[0].replaceAll('/', '-')
        // 焦晓宇的锅，end日期要加一天
        params['end'] = this.getNewDay(this.queryForm.dateRange[1], 1).replace('/', '-')
      }
      getDraftList(this.pageSize, page, params).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    confirmDelete(tid) {
      this.$confirm('此操作将删除该工单草稿, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDraft(tid).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          if (this.list.length === 1) {
            this.currentPage--
          }
          this.fetchData(this.currentPage)
        })
      })
    }
  }
}
</script>
